package net.lesscoding.client;

import cn.hutool.core.util.RandomUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import net.lesscoding.common.Const;

/**
 * @author eleven
 * @date 2024/10/29 14:48
 * @apiNote
 */
@Slf4j
public class HelloWorldClient {
    public static void main(String[] args) {
        send();
        log.info("发送完毕");
    }

    private static void send() {
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap()
                    .group(workerGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel channel) throws Exception {
                            channel.pipeline()
                                    .addLast(new ChannelInboundHandlerAdapter() {
                                        @Override
                                        public void channelActive(io.netty.channel.ChannelHandlerContext ctx) throws Exception {
                                            log.info("客户端连接成功");
                                            String str = "";
                                            for (int i = 0; i < 5; i++) {
                                                str += RandomUtil.randomString(RandomUtil.BASE_CHAR, RandomUtil.randomInt(10, 40))
                                                        + "\n";
                                            }
                                            ByteBuf buffer = ctx.alloc().buffer().writeBytes(str.getBytes());
                                            ctx.writeAndFlush(buffer);

                                        }
                                    });
                        }
                    });

            ChannelFuture future = bootstrap.connect(Const.HOST, Const.PORT)
                    .sync();
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            workerGroup.shutdownGracefully();
        }
    }
}
